﻿#include "judgequestion.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QLabel>
#include <QRadioButton>
#include <QButtonGroup>

JudgeQuestion::JudgeQuestion(QObject *parent)
    : Question{parent}
{
    m_type = TrueFalse;  // 设置题型为判断题
    m_typeString = u8"判断题";  // 设置题型字符串，用于分类显示
    m_typeId = TYPE_JUDGE;  // 设置题型ID为2（判断题）
}


bool JudgeQuestion::fromJson(const QJsonObject &json)
{
    // 解析基本信息
    m_id = json.value("id").toInt();
    m_stem = json.value("content").toString();
    
    // 解析正确答案
    m_correctAnswer = json.value("rightAnswer").toString();
    
    // 确保必要字段都有值
    if (m_id <= 0) {
        qWarning() << u8"判断题ID无效:" << m_id;
    }
    
    if (m_stem.isEmpty()) {
        qWarning() << u8"判断题内容为空，ID:" << m_id;
    }
    
    // 即使部分字段有问题，也返回true，让题目可以显示
    //qDebug() << u8"判断题解析成功，ID:" << m_id << u8"内容:" << m_stem.left(20) << u8"......";
    return true;
}



QJsonObject JudgeQuestion::toJson() const
{
    QJsonObject json = Question::toJson();
    // 添加判断题特有的数据
    json.value("rightAnswer") = m_correctAnswer;
    if (!m_userAnswer.isEmpty()) {
        json.value("studentAnswer") = m_userAnswer;
    }
    return json;
}



QWidget *JudgeQuestion::createWidget(QWidget *parent)
{
    QWidget *widget = new QWidget(parent);
    widget->setProperty("class", "question-container");
    
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    // 显示题目内容
    QLabel *contentLabel = new QLabel(m_stem, widget);
    contentLabel->setWordWrap(true);
    contentLabel->setObjectName("questionContent");
    layout->addWidget(contentLabel);
    
    // 创建单选按钮组
    QWidget *optionsWidget = new QWidget(widget);
    QHBoxLayout *optionsLayout = new QHBoxLayout(optionsWidget);
    
    QRadioButton *trueButton = new QRadioButton(u8"对", optionsWidget);
    QRadioButton *falseButton = new QRadioButton(u8"错", optionsWidget);
    
    optionsLayout->addWidget(trueButton);
    optionsLayout->addWidget(falseButton);
    optionsLayout->addStretch();
    
    layout->addWidget(optionsWidget);
    layout->addStretch();
    
    // 设置按钮组，确保只能选择一个
    QButtonGroup *buttonGroup = new QButtonGroup(widget);
    buttonGroup->addButton(trueButton, 0);
    buttonGroup->addButton(falseButton, 1);
    
    // 如果有用户答案，设置选中状态
    if (m_userAnswer ==u8"正确" || m_userAnswer == u8"对" || m_userAnswer == u8"true" || m_userAnswer == u8"1") {
        trueButton->setChecked(true);
    } else if (m_userAnswer == u8"错误" || m_userAnswer == u8"错" || m_userAnswer == u8"false" || m_userAnswer == u8"0") {
        falseButton->setChecked(true);
    }
    
    // 连接信号槽
    connect(trueButton, &QRadioButton::toggled, [=](bool checked) {
        if (checked) {
            setUserAnswer(u8"对");
        }
    });
    
    connect(falseButton, &QRadioButton::toggled, [=](bool checked) {
        if (checked) {
            setUserAnswer(u8"错");
        }
    });
    
    return widget;
}

